<template>
  <div>
    <div class="card" style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-input v-model="data.title" style="width: 300px; margin-right: 10px" placeholder="请输入标题查询"></el-input>
      <el-input v-model="data.content" style="width: 300px; margin-right: 10px" placeholder="请输入内容查询"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <div style="margin-bottom: 10px">
        <el-button type="primary" style="margin-left: 10px" @click="handleAdd">新 增</el-button>
        <el-button type="danger" style="margin-left: 10px" @click="delBatch">批量删除</el-button>
        <el-button type="info" style="margin-left: 10px">导 入</el-button>
        <el-button type="success" style="margin-left: 10px">导 出</el-button>
      </div>
      <el-table :data="data.noticeData" stripe @selection-change="handleSelectionChange"  style="width: 100%" >
        <el-table-column type="selection"  width="55" />
        <el-table-column label="编号" prop="noticeId" width="150"></el-table-column>
        <el-table-column label="公告标题" prop="title" show-overflow-tooltip></el-table-column>
        <el-table-column label="公告内容" prop="content" show-overflow-tooltip></el-table-column>
        <el-table-column label="发布时间" prop="createTime" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button :icon="Edit" circle type="primary" @click="handleUpdate(scope.row)"></el-button>
            <el-button :icon="Delete" circle type="danger" @click="del(scope.row.noticeId)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination
          @current-change="load"
          @size-change="load"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="data.total"
      />
    </div>

    <el-dialog title="信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form ref="formRef" :rules="data.rules" :model="data.form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="公告标题" prop="title">
          <el-input v-model="data.form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input type="textarea" :rows="5" v-model="data.form.content" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="data.formVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">保 存</el-button>
      </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import {ElMessageBox, ElMessage} from "element-plus";
import alovaInstance from "@/utils/request.js";
import {Delete, Edit} from "@element-plus/icons-vue";


const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  form: {},
  noticeData: [],
  ids:[],
  title: '',
  content:'',
  rules: {
    title: [
      {required: true, message: '请输入公告标题', trigger: 'blur'},
    ],
    content: [
      {required: true, message: '请输入公告内容', trigger: 'blur'},
    ]
  },
})

const formRef = ref();

const load = () =>{
  alovaInstance.Get('/collegeAdminNotice/selectPage', {
    params: {
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      title:data.title,
      content:data.content
    }
  }).then(res => {
    if (res.code === '200') {
      data.noticeData = res.data?.list
      data.total = res.data?.total
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
}

//重置输入框操作方法
const reset = () =>{
  data.title = ''
  data.content = ''
  //重新渲染数据
  load()
}

//新增操作
const handleAdd = () =>{
  //显示新增对话框
  data.formVisible = true
  //防止有脏数据
  data.form = {}
}

//更新（编辑）操作
const handleUpdate = (row) =>{
  //深拷贝一个新的对象用于编辑。这样就不会影响行对象
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

//对话框的保存按钮事件
const save = () =>{
  formRef.value.validate((valid)=>{
    //通过校验才能点击更新或新增的保存操作
    if(valid){
      //有id进行更新操作。无id进行新增操作
      data.form.noticeId ? update() : add()
    }
  })
}

// 新增（保持不变）
const add = () => {
  data.form.createBy = data.user.username
  alovaInstance.Post('/collegeAdminNotice/addNotice', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 更新（修复）
const update = () => {
  data.form.updateBy = data.user.username
  alovaInstance.Put('/collegeAdminNotice/updateNotice', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      setTimeout(() => { location.reload(); }, 500);
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
    data.formVisible = false
  });
}

// 删除（修改URL路径）
const del = (noticeId) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/collegeAdminNotice/deleteNotice/${noticeId}?updateBy=${data.user.username}`).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

// 批量选择（保持不变）
const handleSelectionChange = (rows) =>{  //返回选中的行对象数组
  console.log(rows)
  //从选中的行对象中取出所有的id，组成一个新数组！
  //使用map函数(数组内置函数)
  //遍历rows数组，将每个元素（行对象）的id属性值提取出来，组成一个新的数组。并赋值给存储id的数组中
  data.ids = rows.map(row => row.noticeId)
  console.log(data.ids)
}

// 批量删除（修改URL路径）
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选中需删除的数据')
    return
  }
  ElMessageBox.confirm('批量删除数据后无法恢复，您确认删除吗？', '批量删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/collegeAdminNotice/deleteNoticeBatch/${data.user.username}`, data.ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

load()

</script>